package shared;

import java.util.Random;

public class MathHelper
{

    /**
     * Selects a random index from the prob vector,
     * probability of getting i = probVector[i]
     *
     * @param probVector normalized probability vector
     * @return random index
     */
    public static int selectPVIndex(double[] probVector)
    {
        double sums[] = new double[probVector.length];
        sums[0] = probVector[0];
        for (int i = 1; i < probVector.length; i++)
        {
            sums[i] = sums[i - 1] + probVector[i];
        }

        if (Math.abs(1 - sums[sums.length - 1]) > 0.001)
        {
            System.err.println("Error: non normalized probVector passed to shared.MathHelper.selectPVIndex");
        }


        Random r = new Random();
        double d = r.nextDouble();
        for (int i = 0; i < probVector.length - 1; i++)
        {
            if (d <= sums[i])
                return i;

        }
        return probVector.length - 1;
    }


    public static double clamp(double val, double min, double max)
    {
        return val < min ? min : val > max ? max : val;
    }

    public static double moment(double[] values, int moment)
    {
        double avg = average(values);

        double sum = 0;
        for (double v : values)
        {
            sum += Math.pow(v - avg, moment);
        }

        return sum / values.length;
    }

    public static double stdDev(double[] values)
    {
        return Math.sqrt(moment(values, 2));
    }

    public static double average(double[] values)
    {
        double sum = 0;
        for (double v : values)
        {
            sum += v;
        }
        return sum / values.length;
    }


}
